#include "datareceiver.h"
#include <QDebug>
#include <stdio.h>

DataReceiver::DataReceiver(QObject *parent) :
    QThread(parent)
{
}

void DataReceiver::run()
{
    m_measures.clear();

    // Start
    m_port->write(QByteArray(1,20));

    uint32_t block;
    measure_t measure;

    while(1)
    {
        uint16_t aux;

        if(m_port->bytesAvailable()<4)
        {
            msleep(50);
            continue;
        }
        QByteArray array=m_port->read(sizeof(block));
        block=array.toHex().toUInt(0,16);

        qDebug() << "read:\t"  << QString(array.toHex()) << "\t" << block;

        if(block==0x70000000)
            break;

        //
        // Temperature
        //
        aux=(block >> 16);
        block-=(aux << 16);

        measure.temperature=(aux>>1)&0x7F;

        if(aux&0x01)
            measure.temperature+=0.5;

        if(aux&0x100)
            measure.temperature-=measure.temperature;

        //
        // WindDirection
        //
        aux=(block >> 7);
        block-=(aux << 7);

        measure.direction=aux;

        //
        // WindSpeed
        //
        measure.speed= block * 0.765;

        m_measures.push_back(measure);
    }
    exit();
}
